package com.ziiwee.reduce.rest.jpa;

import com.ziiwee.reduce.rest.AbstractResourceController;
import com.ziiwee.reduce.rest.Resource;
import com.ziiwee.reduce.rest.ResourceService;
import com.ziiwee.reduce.rest.ResourceServiceNotFindException;
import org.springframework.beans.factory.annotation.Autowired;

public class JpaResourceController<T extends Resource<ID>, ID> extends AbstractResourceController<T, ID> {

    @Autowired
    protected JpaDataAccessor dao;

    private JpaResourceService<T, ID> service;

    @Override
    public ResourceService<T, ID> getService() {
        if (service == null) {
            Class<T> entityClass = getResourceType();
            if (!dao.support(entityClass)) {
                throw new ResourceServiceNotFindException(String.format("类型 %s 不是 @Entity", entityClass));
            }
            this.service = new JpaResourceService<>(entityClass, dao);
        }
        return service;
    }
}
